package dianmobile.eistarandroid;

import android.app.Activity;
import android.app.Application;
import android.content.Context;

import com.android.volley.cookies.Cookie;
import com.android.volley.cookies.CookiesManager;
import com.android.volley.cookies.OnCookiesDataChangedListener;
import java.util.ArrayList;
import java.util.List;

import dianmobile.eistarandroid.beans.BoardItemEntity;
import dianmobile.eistarandroid.network.request.ByhhAndroidRequest;
import dianmobile.eistarandroid.network.request.RequestFactory;
import dianmobile.eistarandroid.usermanager.LoginManager;
import dianmobile.eistarandroid.utils.DataUtils;
import im.fir.sdk.FIR;

public class ByhhAndroidApplication extends Application {

    private LoginManager loginManager = null;
    /**订阅列表  用于在版面列表里显示订阅版面 //TODO 从缓存里读初值*/
    private List<BoardItemEntity> subscriptionList = new ArrayList<>();
    /**保存当前登录的用户名*/
    private String loginUserName;
    /**保存程序所有的activity，用于退出时全部杀死*/
    private List<Activity> activityList = new ArrayList<>();

    public LoginManager getLoginManager() {
        if (loginManager == null)
            loginManager = new LoginManager(getApplicationContext());
        return loginManager;
    }

    public static ByhhAndroidApplication acquire(Context context) {
        return (ByhhAndroidApplication) context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        FIR.init(this);
        super.onCreate();

        initCookiesCache();
        initByhhCookieCache();
    }

    /** this is cookies cache of the application. */
    private List<Cookie> cookies;

    /**
     * init the volley's CookiesManager module, and let it use the cookies cache of the application.
     */
    private void initCookiesCache() {
        cookies = new ArrayList<>();

        CookiesManager.initCookiesManager(this, new OnCookiesDataChangedListener() {
            @Override
            public void saveCookies(List<Cookie> cookies) {
                addCookies(cookies);
            }

            @Override
            public String getCookiesHeader(String url) {
                return loadCookiesHeader(url);
            }
        });
    }

    /**
     * invoke this method to let {@link ByhhAndroidRequest}
     * the cookies data cache.
     */
    private void initByhhCookieCache() {
        RequestFactory.setOnCookiesDataChangedListener(new OnCookiesDataChangedListener() {
            @Override
            public void saveCookies(List<Cookie> cookies) {
                addCookies(cookies);
            }

            @Override
            public String getCookiesHeader(String url) {
                return loadCookiesHeader(url);
            }
        });
    }

    /**
     * add and save cookies to cache of application.
     * @param newCookies
     */
    public void addCookies(List<Cookie> newCookies) {
        if (newCookies == null)
            throw new NullPointerException("you can not add a null cookies");

        if (cookies == null)
            throw new IllegalStateException("you must init cookies cache before adding Cookies");

        if (cookies.size() == 0)
            cookies.addAll(newCookies);
        else {
            for (Cookie cookie : newCookies) {
                boolean isModifyStoreData = false;
                if (cookies.contains(cookie)) {
                    // update stored cookie data
                    for (Cookie storedCookie : cookies) {
                        if (storedCookie.equals(cookie)) {
                            storedCookie.setValue(cookie.getValue());
                            storedCookie.setDomain(cookie.getDomain());
                            storedCookie.setExpires(cookie.getExpires());
                            storedCookie.setPath(cookie.getPath());

                            isModifyStoreData = true;
                        }
                    }
                }

                if (!isModifyStoreData)
                    cookies.add(cookie);
            }
        }
    }

    /**
     * load cookies data from application's cache.
     * @param url
     * @return
     */
    public String loadCookiesHeader(String url) {
        List<Cookie> cookies;
        if (this.cookies != null && this.cookies.size() > 0) {
            cookies = this.cookies;
            StringBuilder cookieStr = new StringBuilder();
            for (int i = 0; i < cookies.size(); i++) {
                if (DataUtils.checkCookie(url, cookies.get(i))) {
                    if (i == cookies.size() - 1) {
                        cookieStr.append(cookies.get(i).getKey() + "="
                                + cookies.get(i).getValue());
                    } else {
                        cookieStr.append(cookies.get(i).getKey() + "="
                                + cookies.get(i).getValue() + ";");
                    }
                }
            }
            return cookieStr.toString();
        }

        return null;
    }

    /**
     * to let client clear user's login state.
     */
    public void logout() {
        // clear cookies that stored in the client.
        cookies.clear();

        LoginManager.setIsLogin(false);
    }

    public List<BoardItemEntity> getSubscriptionList() {
        return subscriptionList;
    }

    public void setSubscriptionList(List<BoardItemEntity> subscriptionList) {
        this.subscriptionList = subscriptionList;
    }

    public String getLoginUserName() {
        return loginUserName;
    }

    public void setLoginUserName(String loginUserName) {
        this.loginUserName = loginUserName;
    }

    public List<Activity> getActivityList() {
        return activityList;
    }

}
